package com.wuxiaolong.wechat.service.impl;

import com.alibaba.fastjson.JSON;
import com.wuxiaolong.wechat.common.Constants;
import com.wuxiaolong.wechat.model.BaseMessage;
import com.wuxiaolong.wechat.model.NewsItem;
import com.wuxiaolong.wechat.model.NewsMessage;
import com.wuxiaolong.wechat.model.TextMessage;
import com.wuxiaolong.wechat.model.juhe.*;
import com.wuxiaolong.wechat.service.JuheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Description:
 *
 * @author Leo
 * @date 2020-02-13
 */
@Service
@Slf4j
public class JuheServiceImpl implements JuheService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${juhe.robot.chat.url}")
    private String chatUrl;
    @Value("${juhe.robot.chat.appKey}")
    private String chatAppKey;

    @Value("${juhe.robot.weChatSelection.url}")
    private String wcsUrl;
    @Value("${juhe.robot.weChatSelection.appKey}")
    private String wcsAppKey;

    @Value("${juhe.robot.oilPrice.url}")
    private String oilPriceUrl;
    @Value("${juhe.robot.oilPrice.appKey}")
    private String oilPriceAppKey;

    @Value("${juhe.robot.headlineNews.url}")
    private String headlineNewsUrl;
    @Value("${juhe.robot.headlineNews.appKey}")
    private String headlineNewsAppKey;


    /**
     * 聊天机器人
     * @param requestMap
     * @return
     */
    @Override
    public String chat(Map<String, String> requestMap){
        try{
            // 聊天机器人
            String tempUrl = chatUrl
                    +"?key=" +chatAppKey
                    +"&info="+requestMap.get("Content")
                    +"&dtype="+Constants.REQ_DATA_TYPE_JSON
                    +"&userid="+requestMap.get("FromUserName");


            log.info("机器人请求参数：{}", tempUrl);
            ParameterizedTypeReference<JuheResp<QARobotRespResult>> typeRef = new ParameterizedTypeReference<JuheResp<QARobotRespResult>>() {};
            ResponseEntity<JuheResp<QARobotRespResult>> resp = restTemplate.exchange(tempUrl, HttpMethod.GET,null,typeRef);
            log.info("机器人响应参数：{}", JSON.toJSONString(resp));

            if(resp != null && resp.getBody() != null && resp.getBody().getResult() != null && ! StringUtils.isEmpty(resp.getBody().getResult().getText())){
                return resp.getBody().getResult().getText();
            }
            return Constants.CHAT_ROBOT_DEFAULT_RESP;

        }catch (Exception e){
            log.error("机器人回答不了",e);
            return Constants.CHAT_ROBOT_DEFAULT_RESP;
        }
    }

    /**
     * 微信精选    图文消息只能回复一条
     */
    @Override
    public BaseMessage weChatSelection(Map<String, String> requestMap){

        try{

            String tempUrl = wcsUrl
                    +"?key=" +wcsAppKey
                    +"&dtype="+Constants.REQ_DATA_TYPE_JSON
                    +"&pno=100"
                    +"&ps=10";

            log.info("微信精选请求参数：{}", tempUrl);
            ParameterizedTypeReference<JuheResp<WeChatSelectionRespResult<SelectionContent>>> typeRef = new ParameterizedTypeReference<JuheResp<WeChatSelectionRespResult<SelectionContent>>>() {};
            ResponseEntity<JuheResp<WeChatSelectionRespResult<SelectionContent>>> resp = restTemplate.exchange(tempUrl, HttpMethod.GET,null,typeRef);
            log.info("微信精选响应参数：{}", JSON.toJSONString(resp));

            if(resp != null && resp.getBody() != null && resp.getBody().getResult() != null && resp.getBody().getResult().getList() != null && resp.getBody().getResult().getList().size() != 0){

                // 取第一条
                SelectionContent content = resp.getBody().getResult().getList().get(0);

                List<NewsItem> articles = new ArrayList<>();
                articles.add(new NewsItem(content.getTitle(),"推荐",
                        "https://pic4.zhimg.com/v2-11166ed733e4b24898edf4da6bbeeb50_400x224.jpg",content.getUrl()));
                NewsMessage nm = new NewsMessage(requestMap,articles);
                return nm;
            }


        }catch (Exception e){
            log.error("微信精选异常",e);
        }
        return null;
    }

    /**
     * 今日油价
     */
    @Override
    public BaseMessage todayOilPrice(Map<String, String> requestMap){
        try{

            String tempUrl = oilPriceUrl +"?key=" +oilPriceAppKey;

            log.info("今日油价请求参数：{}", tempUrl);
            ParameterizedTypeReference<JuheResp<List<Map<String,String>>>> typeRef = new ParameterizedTypeReference<JuheResp<List<Map<String,String>>>>(){};
            ResponseEntity<JuheResp<List<Map<String,String>>>> resp = restTemplate.exchange(tempUrl, HttpMethod.GET,null,typeRef);
            log.info("今日油价响应参数：{}", JSON.toJSONString(resp));

            if(resp != null && resp.getBody() != null && resp.getBody().getResult() != null && resp.getBody().getResult().size() != 0 ){

                String city = requestMap.get("Content").split(":")[1];

                for(Map<String,String> temp : resp.getBody().getResult()){
                    if(! StringUtils.isEmpty(temp.get("city")) && temp.get("city").matches("^.*"+city+".*$")){
                        return new TextMessage(requestMap,JSON.toJSONString(temp).replace("\\s",""));
                    }
                }

                return new TextMessage(requestMap,"省份名称有误，格式：'油价:安徽'");
            }


        }catch (Exception e){
            log.error("今日油价异常",e);
        }
        return new TextMessage(requestMap,"今日油价查询失败");

    }

    /**
     * 新闻头条
     */
    @Override
    public BaseMessage headlineNews(Map<String, String> requestMap){
        try{

            String tempUrl = headlineNewsUrl +"?type=top&key=" +headlineNewsAppKey;

            log.info("新闻头条请求参数：{}", tempUrl);
            ParameterizedTypeReference<JuheResp<HeadlineNews<HeadlineNewsContent>>> typeRef = new ParameterizedTypeReference<JuheResp<HeadlineNews<HeadlineNewsContent>>>(){};
            ResponseEntity<JuheResp<HeadlineNews<HeadlineNewsContent>>> resp = restTemplate.exchange(tempUrl, HttpMethod.GET,null,typeRef);
            log.info("新闻头条响应参数：{}", JSON.toJSONString(resp));

            if(resp != null && resp.getBody() != null && resp.getBody().getResult() != null
                    && resp.getBody().getResult().getData() != null && resp.getBody().getResult().getData().size() != 0){

                // 取第一条
                HeadlineNewsContent hdc = resp.getBody().getResult().getData().get(0);

                List<NewsItem> articles = new ArrayList<>();
                articles.add(new NewsItem(hdc.getTitle(),"头条",
                        hdc.getThumbnail_pic_s(),hdc.getUrl()));
                NewsMessage nm = new NewsMessage(requestMap,articles);
                return nm;
            }


        }catch (Exception e){
            log.error("新闻头条异常",e);
        }
        return new TextMessage(requestMap,"新闻头条查询失败");

    }
}
